package service

import (
	"context"
	"errors"
	"shop-server/basic/config"
	"shop-server/basic/pkg"
	__ "shop-server/basic/proto"
	"shop-server/handel/models"
)

type Server struct {
	__.UnimplementedStreamGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) ShopAdd(_ context.Context, in *__.ShopAddReq) (*__.ShopAddResp, error) {

	var findShop models.Shop
	if err := findShop.FindShopAdd(config.DB, in.Phone); err != nil {
		return nil, err
	}
	if findShop.Phone == in.Phone {
		return nil, errors.New("手机号用户已存在,注册失败")
	}
	shop := models.Shop{
		Phone:    in.Phone,
		Password: pkg.Md5str1(in.Password),
		Title:    in.Title,
	}
	if err := shop.ShopAddBy(config.DB); err != nil {
		return nil, err
	}
	return &__.ShopAddResp{
		ShopId: int64(shop.ID),
	}, nil
}

func (s *Server) ShopLogin(_ context.Context, in *__.ShopLoginReq) (*__.ShopLoginResp, error) {

	var findShop models.Shop
	if err := findShop.FindShopAdd(config.DB, in.Phone); err != nil {
		return nil, err
	}
	if findShop.Phone != in.Phone {
		return nil, errors.New("手机号错误,登录失败")
	}
	
	shop := models.Shop{
		Phone:    in.Phone,
		Password: pkg.Md5str1(in.Password),
	}
	if err := shop.ShopFind(config.DB); err != nil {
		return nil, err
	}
	return &__.ShopLoginResp{
		ShopId: int64(shop.ID),
	}, nil
}
